package id.ac.amikom.amikomsocial;

import id.ac.amikom.libs.AdemDBHelper;
import id.ac.amikom.libs.AdemInet;
import id.ac.amikom.libs.AdemServiceHelper;
import id.ac.amikom.libs.CustomAdapter;
import id.ac.amikom.libs.DateParse;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AdemShoutActivity extends ListActivity {

	private ListAdapter adapter;
	private AdemDBHelper db = null;

	private String value = null;
	private String id = null;

	private String[] nid;
	private String[] alias;
	private String[] msg;

	private class GetDataTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... params) {

			AdemServiceHelper srv = new AdemServiceHelper(
					AdemShoutActivity.this);
			srv.getShoutService();
			
			
			return null;

		}

		@Override
		protected void onPostExecute(Boolean result) {
			setList();

			((PullToRefreshListView) getListView()).onRefreshComplete();
			super.onPostExecute(result);

		}

	}

	private class PostDataTask extends AsyncTask<Void, Void, Boolean> {

		ProgressDialog dialog = new ProgressDialog(AdemShoutActivity.this);
		boolean result = false;
		String txt = null;

		@Override
		protected Boolean doInBackground(Void... params) {

			if (value.trim().equals("")) {
				txt = "Shout Message Required";
				result = false;
			} else {

				AdemServiceHelper srv = new AdemServiceHelper(
						AdemShoutActivity.this);

				if (srv.postShoutService(id, value)) {
					result = true;

				} else {
					txt = "No Internet Connection";
					result = false;
				}

			}

			return result;

		}

		protected void onPreExecute() {
			this.dialog.setMessage("Post Data..");
			this.dialog.show();
		}

		@Override
		protected void onPostExecute(Boolean result) {

			if (result) {
				new GetDataTask().execute();
			} else {
				Toast.makeText(AdemShoutActivity.this, txt, Toast.LENGTH_LONG)
						.show();

			}

			this.dialog.dismiss();
		}

	}

	private class GetImageTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... params) {
			Cursor cr = db.getUserShout();
			startManagingCursor(cr);

			AdemInet inet = new AdemInet();

			if (cr.moveToFirst()) {
				do {

					inet.downloadImage(cr.getString(cr.getColumnIndex("foto")),
							cr.getString(cr.getColumnIndex("nid")) + "_.png");

				} while (cr.moveToNext());
			}

			cr.close();

			return null;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.adem_list_shout);
		
		//getListView().setOnCreateContextMenuListener(this);

		((PullToRefreshListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {
					public void onRefresh() {
						new GetDataTask().execute();
					}
				});

		db = new AdemDBHelper(this);

		new GetImageTask().execute();

		Cursor c = db.getLogin();

		if (c.getCount() > 0) {
			if (c.moveToFirst()) {
				do {

					id = c.getString(c.getColumnIndex("usr"));

				} while (c.moveToNext());
			}
		}

		c.close();

		setList();

		db.close();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.adem_menu_shout, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.id_new:

			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("Shout Now!");

			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(
					R.layout.adem_dialog_shout, null);
			final EditText postText = (EditText) textEntryView
					.findViewById(R.id.shout_txt);

			alert.setView(textEntryView);

			alert.setPositiveButton("Post",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							value = postText.getText().toString();
							new PostDataTask().execute();

						}
					});

			alert.show();

			return true;
		case R.id.id_login:

			startActivity(new Intent(AdemShoutActivity.this,
					AdemLoginActivity.class));
			finish();

			return true;
		case R.id.id_setting:
			startActivity(new Intent(AdemShoutActivity.this,
					AdemSettingActivity.class));
			finish();

			return true;
		case R.id.id_about:
			Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.adem_info);
			dialog.setTitle("Amikom Social");
			dialog.setCancelable(true);
			dialog.show();

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	public void setList() {
		try {

			Cursor cr = db.getShout();
			startManagingCursor(cr);

			ArrayList<HashMap<String, Object>> newsList = new ArrayList<HashMap<String, Object>>();

			int i = 0;
			nid = new String[cr.getCount()];
			alias = new String[cr.getCount()];
			msg = new String[cr.getCount()];

			if (cr.moveToFirst()) {
				do {

					HashMap<String, Object> map = new HashMap<String, Object>();

					DateParse dp = new DateParse(cr.getString(cr
							.getColumnIndex("time")));

					// use user image if exist
					// start here --->
					File f = new File("/mnt/sdcard/amikom/"
							+ cr.getString(cr.getColumnIndex("nid")) + "_.png");

					if (f.exists())
						map.put("icon",
								"/mnt/sdcard/amikom/"
										+ cr.getString(cr.getColumnIndex("nid"))
										+ "_.png");
					else
						map.put("icon", R.drawable.none);

					// use name alias if exist
					// start here -->
					if (cr.getString(cr.getColumnIndex("alias")).equals("null")) {
						map.put("name", cr.getString(cr.getColumnIndex("name")));
					} else {
						map.put("name",
								cr.getString(cr.getColumnIndex("alias")));
					}

					map.put("msg", cr.getString(cr.getColumnIndex("msg")));
					map.put("via",
							"from " + cr.getString(cr.getColumnIndex("via"))
									+ ", " + dp.parseString());
					newsList.add(map);

					nid[i] = cr.getString(cr.getColumnIndex("nid"));
					alias[i] = cr.getString(cr.getColumnIndex("alias"));
					msg[i] = cr.getString(cr.getColumnIndex("msg"));

					if (alias[i].equals("null")) {
						String[] nm = cr.getString(cr.getColumnIndex("name"))
								.split("\\s+");
						alias[i] = nm[0].toLowerCase();
					}

					i++;

				} while (cr.moveToNext());

			}

			adapter = new CustomAdapter(this, newsList,
					R.layout.adem_list_shout, new String[] { "name", "msg",
							"icon", "via" }, new int[] { R.id.sh_name,
							R.id.sh_msg, R.id.sh_img, R.id.sh_via });

			setListAdapter(adapter);
			registerForContextMenu(getListView());			

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);		
		l.showContextMenuForChild(v);   

	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {								
		
		menu.setHeaderTitle("Shout Option");
		menu.add(Menu.NONE, 0, Menu.NONE, "Re-Shout");
		menu.add(Menu.NONE, 1, Menu.NONE, "Reply");
		menu.add(Menu.NONE, 2, Menu.NONE, "Profile");

	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Shout Now!");

		LayoutInflater factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(
				R.layout.adem_dialog_shout, null);
		final EditText postText = (EditText) textEntryView
				.findViewById(R.id.shout_txt);

		alert.setView(textEntryView);
				
		String postAlias = "@"+alias[info.position-1];
		String postMsg = ":O "+ postAlias + " " +msg[info.position-1];
		
		switch (item.getItemId()) {
		case 0:
			
			postText.setText(postMsg);						
			
			alert.setPositiveButton("Post",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							value = postText.getText().toString();
							new PostDataTask().execute();

						}
					});

			alert.show();

			
			return (true);
		case 1:
			
			postText.setText(postAlias);						
			
			alert.setPositiveButton("Post",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							value = postText.getText().toString();
							new PostDataTask().execute();

						}
					});

			alert.show();

			
			return (true);
		case 2:
			
			Intent i = new Intent(AdemShoutActivity.this, AdemUserActivity.class);
			i.putExtra("nid", nid[info.position-1]);
			finish();
			startActivity(i);
						
			return (true);
		}
						
		return (super.onOptionsItemSelected(item));
	}

}
